package edu.jsnu.operate.controller.ticket;

import beans.PageQuery;
import com.github.pagehelper.PageInfo;
import dto.resDto.JsonData;
import dto.resDto.RespData;
import edu.jsnu.operate.controller.ticket.common.AbstractController;
import edu.jsnu.service.ticket.schedule.domain.Schedule;
import edu.jsnu.service.ticket.schedule.dto.ScheduleReceive;
import edu.jsnu.service.ticket.schedule.dto.ScheduleShow;
import edu.jsnu.service.ticket.schedule.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "ticket/schedule")
public class ScheduleController extends AbstractController {

    @Autowired
    private ScheduleService scheduleService;


    @RequestMapping(value = "schedule.page")
    public String schedulePage() {
        return "ticket/schedule/schedule";
    }

    /**
     * @param model
     * @param id
     * @param flag  新增1，编辑2，详情3
     * @return
     */
    @RequestMapping(value = "save.page")
    public String savePage(Model model, @RequestParam(value = "id", required = false) Integer id,
                           @RequestParam(value = "flag", required = false, defaultValue = "1") Integer flag) {
        if (id != null) {
            ScheduleReceive schedule = ScheduleReceive.scheduleShow2Receive(scheduleService.getScheduleById(id));

            model.addAttribute("schedule", schedule);
        }
        model.addAttribute("flag", flag);
        return "ticket/schedule/save";
    }

    @RequestMapping(value = "schedule.json", method = RequestMethod.GET)
    @ResponseBody
    public RespData scheduleData(PageQuery pageQuery) {
        try {
            List<ScheduleShow> scheduleList = scheduleService.getSchedule(pageQuery);
            PageInfo<ScheduleShow> pageInfo = new PageInfo<>(scheduleList);
            return RespData.success(pageInfo.getList(), pageInfo.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespData.fail("查询场次信息异常，请联系管理员");
    }

    //影片开始时间与结束时间间隔大于影片时长5分钟
    public final long FIVE_MINUTES = 5 * 60 * 1000;

    /*@RequestMapping(value = "save.json", method = RequestMethod.POST)
    @ResponseBody
    public JsonData saveSchedule(ScheduleReceive receive) {
        try {
            String msg = "";
            if (receive.getId() == null) {
                Schedule schedule = ScheduleReceive.receive2Schedule(receive);
                //判断开始时间是否为空，如果为空，默认写入当天的
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (schedule.getStartTime() == null || schedule.getEndTime() == null) {
                    schedule.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()) + " 15:00:00"));
                    schedule.setEndTime(new Date(schedule.getStartTime().getTime() + receive.getDuration() * 60 * 1000 + FIVE_MINUTES));
                }
                if (receive.getTimeFlag() == null || receive.getTimeFlag() == 0) {
                    msg = scheduleService.getFilmTypesetting(schedule, false);

                } else if (receive.getTimeFlag() == 1) {
                    msg = scheduleService.getFilmTypesetting(schedule, true);
                }
            } else {
                //修改场次
                Schedule schedule = ScheduleReceive.receive2Schedule(receive);
                if (schedule.getStartTime() == null && schedule.getEndTime() == null){
                    scheduleService.updateByPrimaryKeySelective(schedule);
                    msg = "保存成功";
                }else {
                    if (receive.getTimeFlag() == null || receive.getTimeFlag() == 0) {
                        msg = scheduleService.getFilmTypesetting(schedule, false);

                    } else if (receive.getTimeFlag() == 1) {
                        msg = scheduleService.getFilmTypesetting(schedule, true);
                    }
                }
            }
            return JsonData.success(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonData.fail("保存场次信息失败，请联系管理员");
    }*/

    @RequestMapping(value = "save.json", method = RequestMethod.POST)
    @ResponseBody
    public JsonData saveSchedule(ScheduleReceive receive) {
        try {
            String msg = "";
            if (receive.getId() != null) {
                //删除掉此条信息，再重新写入
                scheduleService.deleteScheduleById(receive.getId());
            }
            Schedule schedule = ScheduleReceive.receive2Schedule(receive);
            //判断开始时间是否为空，如果为空，默认写入当天的
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (schedule.getStartTime() == null || schedule.getEndTime() == null) {
                schedule.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()) + " 15:00:00"));
                schedule.setEndTime(new Date(schedule.getStartTime().getTime() + receive.getDuration() * 60 * 1000 + FIVE_MINUTES));
            }
            if (receive.getTimeFlag() == null || receive.getTimeFlag() == 0) {
                msg = scheduleService.getFilmTypesetting(schedule, false);
            } else if (receive.getTimeFlag() == 1) {
                msg = scheduleService.getFilmTypesetting(schedule, true);
            }
            return JsonData.success(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonData.fail("保存场次信息失败，请联系管理员");
    }

    @RequestMapping(value = "batchDel.json", method = RequestMethod.POST)
    @ResponseBody
    public JsonData batchDel(Integer[] ids) {
        try {
            return scheduleService.batchDel(ids) > 0 ? JsonData.success("批量删除影片成功") : JsonData.fail("批量删除影片失败，请稍后再试");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonData.fail("批量删除影片失败，请联系管理员");
    }

    //场次的随机插入
    @RequestMapping("insert.page")
    public String insertSchedule(ScheduleReceive scheduleReceive) {
        Schedule schedule = null;
        schedule = ScheduleReceive.receive2Schedule(scheduleReceive);
        boolean flag = false;
        if (scheduleReceive.getTimeFlag() == 1) {
            flag = false;
        } else {
            flag = true;
        }
        //如果数据库当天最后一场为23:59，且还需要随机写入，则会写入错误，待解决
        scheduleService.getFilmTypesetting(schedule, flag);
        return "";
    }

    @RequestMapping(value = "del.json", method = RequestMethod.POST)
    @ResponseBody
    public JsonData delSchedule(Integer id){
        int result = scheduleService.deleteScheduleById(id);
        try{
            return result > 0 ? JsonData.success("数据删除成功") : JsonData.fail("数据删除失败");
        }catch(Exception e){
            e.printStackTrace();
        }
        return JsonData.fail("数据删除失败，请联系管理员");
    }
}
